<template>
  <div class="address-edit">
    <back-title></back-title>
    <van-address-edit :area-list="areaList" show-delete show-set-default :address-info="addressInfo"
      :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @delete="onDelete" />
  </div>
</template>

<script>
  import {
    mapState
  } from 'vuex'
  import axios from '../../../api/http.js'
  import BackTitle from '../../../components/BackHeader/BackTitle.vue'
  import AreaList from '../../../assets/js/areaList.js'
  export default {
    components: {
      BackTitle
    },
    data() {
      return {
        addressId: 0,
        addressInfo: {},
        areaList: AreaList
      }
    },
    methods: {
      async onSave(content) {
        const _this = this
        console.log(content)
        const params = {
          user_id: _this.loginToken.userId,
          consignee: content.name,
          consignee_phone: content.tel,
          default_flag: content.isDefault === true ? '1' : '0',
          province_name: content.province,
          city_name: content.county,
          region_name: content.city,
          detail_address: content.addressDetail
        }
        await axios.put(axios.defaults.baseURI + 'books/useraddress/' + _this.addressId + '/', params).then(res => {
          console.log('res:', res)
          if (res.code === 200) {
            this.$toast.success('修改成功！')
            setTimeout(this.$router.go(-1), 400)
          } else {
            this.$toast.fail('修改失败')
          }
        })
      },
      async onDelete(content) {
        console.log(content)
        await axios.delete(axios.defaults.baseURI + 'books/useraddress/' + this.addressId + '/').then(res => {
          console.log('res:', res)
          if (res.code === 204) {
            this.$toast.success('删除成功！')
            setTimeout(this.$router.go(-1), 400)
          } else {
            this.$toast.fail('删除失败')
          }
        })
      }
    },
    created() {
      this.addressId = this.$route.query.item
      this.address.forEach((value, index) => {
        if (value.address_id === Number(this.addressId)) {
          this.addressInfo = {
            name: value.consignee,
            // province: value.province_name,
            // city: value.city_name,
            // county: value.region_name,
            tel: value.consignee_phone,
            addressDetail: value.detail_address,
            isDefault: value.default_flag === 0
          }
        }
      })
      console.log('addressId:', typeof this.addressId)
      console.log('address:', this.address)
      console.log('addressInfo:', this.addressInfo)
    },
    computed: {
      ...mapState(['address'])
    }
  }
</script>

<style scoped>
  /deep/.set-header-ellipsis {
    visibility: hidden;
  }
</style>
